<?php
namespace app\api\controller;

use app\api\model\wanlshop\Order;
use app\api\model\wanlshop\RefundLog;
use app\common\controller\Api;
use app\common\controller\pay\Julaicai;
use app\common\library\FireFace;
use think\Log;
use think\Request;
use app\api\handler\CurlHandler;
use app\api\model\wanlshop\Pay as PayModel;
use app\api\model\wanlshop\Refund;
use app\api\model\wanlshop\OrderAddress;
use app\api\model\wanlshop\PayOutTrade;
use app\api\model\wanlshop\OrderGoods;
use addons\wanlshop\library\WanlSdk\Common;
use think\Cache;
use app\api\controller\Newsms;
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
//    正尊电子商务有限公司
//    protected $merchantNo = '103363';
//    protected $operatorAccount = '19912537676';
//    protected $salt = 'bsABNVPzwb';
//    protected $authCode = '1423318090000001';
//    protected $refundPassword = '776766';


//  中新国融(山东)农业科技有限公司
    protected $merchantNo = '103448';
    protected $operatorAccount = '18006338679';
    protected $salt = '8Rk5kNrCV9';
    protected $authCode = '1423332140000002';
    protected $refundPassword = '112233';

    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

//        FireFace::update();
        $data = (new FireFace())->random();
//        $data = (new FireFace())->getRow(6);
        if ($data){
            $this->merchantNo = $data['merchantNo'];
            $this->operatorAccount = $data['operatorAccount'];
            $this->salt = $data['salt'];
            $this->authCode = $data['authCode'];
            $this->refundPassword = $data['refundPassword'];
        }
    }

    //火脸支付请求
    public function fire($data){
        $url = 'https://open.lianok.com/open/v1/api/biz/do';
        $handler = new CurlHandler();
        $res = $handler->curlRequest([
            'url'=>$url,
            'method'=>'POST',
            'headers'=>[
                "Content-Type:application/json;charset=UTF-8",
                "User-Agent:API Explorer"
            ],
        ],$data);
        return $res;
    }
    //公共参数
    public function gong($data,$apiName){
        $currentTimestamp = time();
        $formattedDateTime = date("YmdHis", $currentTimestamp);
        $gong = [
            'authCode'=>$this->authCode,
            'requestTime'=>$formattedDateTime,
            'resource'=>$apiName,
            'versionNo'=>1,
        ];
        $sign = $this->encrypt($data,$gong);
        $gong['params'] = json_encode($this->remove_null_values($data));
        $gong['sign'] = $sign;
        $gong = $this->remove_null_values($gong);
        return $gong;
    }
    //获取待签名字符串
    public function getRequestSignContent($req, $keyArr, $valueArr)
    {

        foreach (((array)$req) as $key => $value) {
            if (strlen($key) === strlen(trim($key))) {
                if ($value !== null) {
                    array_push($keyArr, $key);
                    array_push($valueArr, $value);
                }
            }
        }
        array_multisort($keyArr, $valueArr);
        $content = '';
        for ($i = 0; $i < count($keyArr); $i++) {
            $content = $content . $keyArr[$i] . '=' . $valueArr[$i] . '&';
        }
        return $content;
    }
    //生成签名
    private function encrypt($request,$gong)
    {
        $keyArr = array("authCode", "resource", "requestTime", "versionNo");
        $valArr = array($gong['authCode'], $gong['resource'], $gong['requestTime'],$gong['versionNo']);

        $strParams = $this->getRequestSignContent($request, $keyArr, $valArr);
        $strParams = strtolower($strParams);
        $strParams = $strParams .$this->salt;
        return md5($strParams);
    }
    //非null参数的key按照ASCII码进行排序
    private function remove_null_values($a)
    {
        $ret = (is_array($a) ? array() : new stdClass());
        foreach ($a as $k => $v) {
            if (is_array($v) || is_object($v)) {
                if (is_object($ret))
                    $ret->$k = $this->remove_null_values($v);
                else
                    $ret[$k] = $this->remove_null_values($v);
            } elseif (!is_null($v)) {
                if (is_object($ret))
                    $ret->$k = $v;
                else
                    $ret[$k] = $v;
            }
        }
        ksort($ret);
        return $ret;
    }
    //配置小程序appid
    public function appid(){
        $data = [
            'merchantNo'=>$this->merchantNo,
            'operatorAccount'=>$this->operatorAccount,
            'appid'=>'wxf51d01cf670e28d3',
            'channelCode'=>'leShua'
        ];
        $gong = $this->gong($data,'api.hl.merchant.wxpayconfig');
        $res = $this->fire($gong);
        $this->success('成功',$res);
    }
    //开通小程序支付
    public function switchChannel(){
        $code = input('code','leShuaOnline');
        $data = [
            'merchantNo'=>$this->merchantNo,
            'operatorAccount'=>$this->operatorAccount,
            'payWay'=>'wechat',
            'channelCode'=>$code
        ];
        $gong = $this->gong($data,'api.hl.merchant.switchChannel');
        $res = $this->fire($gong);
        $this->success('成功',$res);
    }
    //小程序支付 入口方法
    public function applet($param){
        extract($param);
        $data = [
            'merchantNo'=>$this->merchantNo,
            'operatorAccount'=>$this->operatorAccount,
            'businessOrderNo'=>$order_no,  //订单号
            'payAmount'=>$price,  //支付金额
            'payWay'=>'wechat',  //支付类型
            'appId'=>'wxf51d01cf670e28d3',
            'openId'=>$openid,  //openid
            'notifyUrl'=>'https://xinweidu.enjoysix.com/api/pay/notify'
        ];
        $gong = $this->gong($data,'api.hl.order.pay.applet');
        $res = $this->fire($gong);
        if ($res['httpCode'] == 200){
            return json_decode($res['body']);
        }else{
            Log::error($res['body']);
            return false;
        }
    }
    //退款
    public function refund($refund_id){
        $currentTimestamp = time();
        $formattedDateTime = date("YmdHis", $currentTimestamp);
        $refund = Refund::where('id',$refund_id)->find();
        $reund_no = $formattedDateTime.$refund->id;
        $payoutTrade = PayOutTrade::where('order_id',$refund->order_id)->find();
        $data = [
            'businessOrderNo'=>$payoutTrade->out_trade_no,
            'businessRefundNo'=>$reund_no,
            'refundAmount'=>$refund->price,
            'refundPassword'=>$this->refundPassword,  //管理密码
            'merchantNo'=>$this->merchantNo,
            'operatorAccount'=>$this->operatorAccount,
            'notifyUrl'=>'https://xinweidu.enjoysix.com/api/pay/notify'
        ];
        Log::error($data,'同意退款火脸入参');
        $gong = $this->gong($data,'api.hl.order.refund.operation');
        $res = $this->fire($gong);
        Log::error($res,'同意退款火脸');
        return $res;
    }
    //回调
    public function notify(Request $request){
        // 获取所有传递的参数
        $params = $request->param();
        Log::error($params,'火脸回调');
        if($params['code'] == 200){
            $decodedJsonString = html_entity_decode($params['respBody']);
            $data = json_decode($decodedJsonString,true);
            Log::error($data,'火脸回调数据');
            if($data){
                $payoutTrade = PayOutTrade::where('out_trade_no',$data['businessOrderNo'])->find();
                $pay = PayModel::where('id',$payoutTrade->pay_id)->find();
                if($payoutTrade){
                    $order = Order::where('id',$payoutTrade->order_id)->find();
                    if($data['notifyType'] == 'pay'){
                        $payoutTrade->transaction_id = $data['topChannelOrderNo'];
                        $payoutTrade->save();
                        $pay->trade_no = $data['orderNo'];
                        $pay->pay_type = $data['payWay']=='wechat'?1:2;
                        if($data['orderStatus'] == 2){   //支付成功
                            if ($order->state == '1'){  //订单状态
                            $pay->pay_state = 1;
                            $order->state = 2;
                            Log::error('开始发送短信');
                            $orderAddress = OrderAddress::where('order_id',$order->id)->find();
                            $orderGood = OrderGoods::where('order_id',$order->id)->find();
//                            $smsModel = Sms::where('order_no',$order->order_no)->find();
//                            $sign = '【新维度】尊敬的 '.$orderAddress->name.'，您的商品'.$orderGood->title.'已经下单成功！点击查看https://xinweidu.lifeepay.com/h5/#/pages/page/success?order_no='.$order->order_no;
                            $sign = '【新维度】尊敬的 '.$orderAddress->name.'，您的商品'.$orderGood->title.'已经下单成功！点击查看https://xinweidu.lifeepay.com/h5e/#/pages/page/success?order_no='.$order->order_no;
                            $pay->actual_payment =  $data['payAmount'];
                            $pay->save();
                            $order->paymenttime = $data['payTime'];
                            $order->save();

                            $smsModel = \app\api\model\wanlshop\Sms::where('order_no',$order->order_no)->find();
                            if(!$smsModel){
                                $addSms = \app\api\model\wanlshop\Sms::create([
                                    'order_no'=>$order->order_no,
                                    'is_success'=>'0',
                                    'content'=>$sign,
                                    'mobile'=>$orderAddress->mobile
                                ]);

                                //发送短信
                                $sms = new Newsms();
                                $smsResult = $sms->send(['mobile'=>$orderAddress->mobile,'sign'=>$sign,'order_no'=>$order->order_no]);

                                if ($smsResult && isset($smsResult['message']) && isset($smsResult['message'][0]) && $smsResult['message'][0] == 'ok'){
                                    $addSms->is_success = '1';
                                    $addSms->save();
                                }

                            }
                            return 'SUCCESS';
                            }
                        }



                    }
                    if ($data['notifyType'] == 'refund'){
                        $refund = Refund::where('order_id',$order->id)->where('order_pay_id',$payoutTrade->pay_id)->find();
                        $OrderGoods = OrderGoods::where('order_id',$order->id)->find();
                        if($refund) {
                            if($data['refundStatus'] == 2){
                                $order->state = 7;
                                $order->save();
                                $OrderGoods->refund_status = 3;
                                $OrderGoods->save();
                                $refund->state = 4;
                                $refund->completetime = strtotime($data['refundTime']);
                                $refund->save();
                                return 'SUCCESS';
                            }
                        }else{
                            Log::error('未找到退款申请');
                        }
                    }
                }
            }
        }

    }

    public function test($order_no)
    {
        $order = (new Order())->where(['order_no'=>$order_no])->find();
        $orderAddress = OrderAddress::where('order_id',$order->id)->find();
        $orderGood = OrderGoods::where('order_id',$order->id)->find();
        $sign = '【新维度】尊敬的 '.$orderAddress->name.'，您的商品'.$orderGood->title.'已经下单成功！点击查看https://xinweidu.lifeepay.com/h5/#/pages/page/success?order_no='.$order->order_no;
        $smsModel = \app\api\model\wanlshop\Sms::where('order_no',$order->order_no)->find();
        if(!$smsModel){
            \app\api\model\wanlshop\Sms::create([
                'order_no'=>$order->order_no,
                'is_success'=>'0',
                'content'=>$sign,
                'mobile'=>$orderAddress->mobile
            ]);

        }
        $this->success('返回成功', $this->request->param());
    }

    // h5预下单
    public function h5()
    {
        // 订单号或订单ID
        $order_no = $this->request->post('order_no');
        $order_ids = $this->request->post('order_id/a');
        $payWay = $this->request->post('pay_way','wechat');
        $domain = $this->request->domain();
        if (!$payWay){
            $payWay = 'wechat';
        }
//        Log::error("订单号");
//        Log::error($order_no);
        if (Cache::store('redis')->has($order_no)){
            Cache::store('redis')->inc("order_no_number".$order_no,1);
            $this->error("订单已失效，请重新下单");
        }else{
            Cache::store('redis')->set("order_no_number".$order_no,1,86400);
            Cache::store('redis')->set($order_no,"order_no".$order_no,86400);
        }
        // 强行支付宝
        $payWay = 'alipay';
        // 获取订单数据
        // 判断权限
        $model_order = model('app\api\model\wanlshop\Order');
        $model_order_goods = model('app\api\model\wanlshop\OrderGoods');
        $model_goods = model('app\api\model\wanlshop\Goods');
        $model_goods_sku = model('app\api\model\wanlshop\GoodsSku');
        $order = $model_order
            ->where('id', 'in', $order_ids)
//            ->where('user_id', $this->auth->id)
            ->select();
        if(!$order){
            $this->error(__('没有找到任何要支付的订单'));
        }
        foreach($order as $item){
            if($item['state'] != 1){
                $this->error(__('订单已支付，或网络繁忙'));
            }
            // 1.0.5升级 修复付款减库存
            foreach($model_order_goods->where('order_id', $item['id'])->select() as $data){
                $redis = Common::redis();
                // 获取sku
                $sku = $model_goods_sku->get($data['goods_sku_id']);
                // 1.1.2升级
                $sku_key = 'goods'.'_'.$sku['goods_id'].'_'.$sku['id'];
                // 查询商品
                $goods = $model_goods
                    ->where(['id' => $data['goods_id'], 'stock' => 'payment'])
                    ->find();
                // 库存计算方式:porder=下单减库存,payment=付款减库存 1.0.8升级
                if($goods) {
                    // 1.1.2升级
                    if($data['number'] > $redis->llen("{$sku_key}")){
                        $this->error("系统繁忙，请稍后抢购！");
                    }else{
                        for ($i = 0; $i < $data['number']; $i ++) {
                            $redis->rpop("{$sku_key}");
                        }
                        $sku->setDec('stock', $data['number']); // 1.0.3升级
                    }
                }
            }
        }

        // 添加第三方支付订单信息
        // 获取支付信息
        $pay = model('app\api\model\wanlshop\Pay')
            ->where('order_id', 'in', $order_ids)
            ->where(['type' => 'goods'])
//            ->where(['user_id' => $this->auth->id])
            ->select();
        // 1.0.8 升级
        $price = 0; // 付款金额
//        $order_no = []; // 订单号
        $pay_id = []; // 交易号
        foreach($pay as $row){
            $price = bcadd($price, $row['price'], 2); // 总价格
//            $order_no[] = $row['order_no']; // 订单集
            $pay_id[] = $row['id']; // 交易集
        }
        $payOutTrade = (new PayOutTrade());
        $payOutTrade->out_trade_no = date('YmdHis'). rand(10000000,99999999). substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $payOutTrade->pay_id = $pay_id;
        $payOutTrade->order_id = $order_ids;
        $payOutTrade->price = $price;
        $payOutTrade->type = 1;
        // 记录火脸账户
        $payOutTrade->mch_id = $this->merchantNo;
        if($payOutTrade->save()){
            // 发起支付
//            $result = (new \app\api\controller\Pay())->applet(['order_no'=>$payOutTrade->out_trade_no,'price'=>$price,'openid'=>$openid]);
            $data = [
                'businessOrderNo' => $payOutTrade->out_trade_no,
                'payAmount' => $price,
//            'remark' => '备注',
                'merchantNo' => $this->merchantNo,
                'operatorAccount' => $this->operatorAccount,
                'notifyUrl' => $domain.'/api/pay/notify',
//            'subject' => '测试商品',
                'payWay' => $payWay,
                'pageNotifyUrl' => $domain.'/h5/#/pages/page/success?order_no='.$order_no, // 重定向地址
//            'itemAmount' => 0.01,
//            'itemQuantity' => 1,
            ];
            $gong = $this->gong($data,'api.hl.order.pay.h5');
            $result = $this->fire($gong);
            $arr = json_decode($result['body']??[],true);
            if ($result['httpCode'] == 200){
                if (isset($arr['data'])){
                    $this->success('',$arr['data']);
                }
            }
            $this->error('',$result);
        }else{
            $this->error('支付失败');
        }
    }

    // h5预下单
    public function julaicaih5()
    {
        // 订单号或订单ID
        $order_no = $this->request->post('order_no');
        $order_ids = $this->request->post('order_id/a');
        $payWay = $this->request->post('pay_way','wechat');
        $domain = $this->request->domain();
        if (!$payWay){
            $payWay = 'wechat';
        }
//        Log::error("订单号");
//        Log::error($order_no);
//        if (Cache::store('redis')->has($order_no)){
//            Cache::store('redis')->inc("order_no_number".$order_no,1);
//            $this->error("订单已失效，请重新下单");
//        }else{
//            Cache::store('redis')->set("order_no_number".$order_no,1,86400);
//            Cache::store('redis')->set($order_no,"order_no".$order_no,86400);
//        }
        // 强行支付宝
        $payWay = 'alipay';
        // 获取订单数据
        // 判断权限
        $model_order = model('app\api\model\wanlshop\Order');
        $model_order_goods = model('app\api\model\wanlshop\OrderGoods');
        $model_goods = model('app\api\model\wanlshop\Goods');
        $model_goods_sku = model('app\api\model\wanlshop\GoodsSku');
        $order = $model_order
            ->where('id', 'in', $order_ids)
//            ->where('user_id', $this->auth->id)
            ->select();
        if(!$order){
            $this->error(__('没有找到任何要支付的订单'));
        }
        foreach($order as $item){
            if($item['state'] != 1){
                $this->error(__('订单已支付，或网络繁忙'));
            }
            // 1.0.5升级 修复付款减库存
            foreach($model_order_goods->where('order_id', $item['id'])->select() as $data){
                $redis = Common::redis();
                // 获取sku
                $sku = $model_goods_sku->get($data['goods_sku_id']);
                // 1.1.2升级
                $sku_key = 'goods'.'_'.$sku['goods_id'].'_'.$sku['id'];
                // 查询商品
                $goods = $model_goods
                    ->where(['id' => $data['goods_id'], 'stock' => 'payment'])
                    ->find();
                // 库存计算方式:porder=下单减库存,payment=付款减库存 1.0.8升级
                if($goods) {
                    // 1.1.2升级
                    if($data['number'] > $redis->llen("{$sku_key}")){
                        $this->error("系统繁忙，请稍后抢购！");
                    }else{
                        for ($i = 0; $i < $data['number']; $i ++) {
                            $redis->rpop("{$sku_key}");
                        }
                        $sku->setDec('stock', $data['number']); // 1.0.3升级
                    }
                }
            }
        }

        // 添加第三方支付订单信息
        // 获取支付信息
        $pay = model('app\api\model\wanlshop\Pay')
            ->where('order_id', 'in', $order_ids)
            ->where(['type' => 'goods'])
//            ->where(['user_id' => $this->auth->id])
            ->select();
        // 1.0.8 升级
        $price = 0; // 付款金额
//        $order_no = []; // 订单号
        $pay_id = []; // 交易号
        foreach($pay as $row){
            $price = bcadd($price, $row['price'], 2); // 总价格
//            $order_no[] = $row['order_no']; // 订单集
            $pay_id[] = $row['id']; // 交易集
        }
        $payOutTrade = (new PayOutTrade());
        $payOutTrade->out_trade_no = date('YmdHis'). rand(10000000,99999999). substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $payOutTrade->pay_id = $pay_id;
        $payOutTrade->order_id = $order_ids;
        $payOutTrade->price = $price;
        $payOutTrade->type = 1;
        // 记录火脸账户
        $payOutTrade->mch_id = $this->merchantNo;
        if($payOutTrade->save()){
            // 发起支付
//            $result = (new \app\api\controller\Pay())->applet(['order_no'=>$payOutTrade->out_trade_no,'price'=>$price,'openid'=>$openid]);
            $result = (new Julaicai())->h5(['mchOrderNo'=>$payOutTrade->out_trade_no,'amount'=>$price,'order_no'=>$order_no]);
            if ($result->code === 0){
                if ($result->data){
                    $this->success('',$result->data->payData);
                }
            }
            $this->error('',$result);
        }else{
            $this->error('支付失败');
        }
    }

    //小程序支付托管下单
    public function preApplet($param){
        extract($param);
        $data = [
            'merchantNo'=>$this->merchantNo,
            'operatorAccount'=>$this->operatorAccount,
            'businessOrderNo'=>$order_no,  //订单号
            'payAmount'=>$price,  //支付金额
            'payWay'=>'wechat',  //支付类型
            'notifyUrl'=>'https://xinweidu.enjoysix.com/api/pay/notify'
        ];
        $gong = $this->gong($data,'api.hl.order.pre.pay.applet');
        $res = $this->fire($gong);
        if ($res['httpCode'] == 200){
            return json_decode($res['body']);
        }else{
            Log::error($res['body']);
            return false;
        }
    }
}